<!-- 蓝牙和位置都需要打开-->
<template>
	<view class="content">
		<button type="primary" @tap="startBluetoothDeviceDiscovery">搜索蓝牙设备</button>
		<button type="warn" @tap="stopBluetoothDevicesDiscovery">停止搜索</button>
		
		<scroll-view class="device_list" scroll-y="true" show-scrollbar="true">
			<radio-group>
				<view v-for="(item,index) in devicesList" :key="index" class="device_item" v-if="item.name.length>0">
					<view style="font-size: 32rpx; color: #333;">
						<radio :value="item.deviceId" @tap="select_deviceId(item)" />{{item.name }}
					</view>
					<view style="font-size: 20rpx">信号强度: {{item.RSSI}}dBm ({{Math.max(100+item.RSSI,0)}}%)</view>
					<view style="font-size: 20rpx">设备名称: {{item.deviceId}}</view>
					<!-- <view style="font-size: 20rpx">可用服务数量: {{item.advertisServiceUUIDs.length || 0}}</view> -->
		
					<radio-group v-if="deviceId===item.deviceId">
						<view v-for="(service,service_index) in serviceList" :key="service_index" style="font-size: 20rpx">
							<radio style="transform:scale(0.7)" :value="service.uuid" @tap="select_service(service)" />{{service.uuid }}
						</view>
					</radio-group>
				</view>
			</radio-group>
		</scroll-view>
		
		<view style="text-align: center;margin-top: 10px;">
			<view>当前连接设备:{{deviceId}}</view>
			<view>服务:{{serviceId}}</view>
			<!-- <view>设备特征值notifyId:{{notifyId}}</view> -->
			<view>writeId:{{writeId}}</view>
			
			<button type="primary" @click="reconnect()">重新连接蓝牙</button>

		</view>
		
		<button type="primary" style="margin-top: 10px;" @tap="pickUpOnce">测试打印模板</button>
		
	</view>
</template>

<script>
	import PrinterJobs from './printerjobs.js'
	import printerUtil from './printerutil.js'
	import Bluetooth from './bluetooth.js'

	let bluetooth = new Bluetooth();

	export default {
		components: {},
		data() {
			return {
				isOpenBle: false, //是否已经打开蓝牙，默认为false
				devicesList: [], //设备列表
				serviceList: [], //服务列表
				deviceId: "", //设备
				serviceId:"",//设备服务
				notifyId:"",//特征值
				writeId:"",//传输数据特征值
			}
		},
		//页面卸载是关闭蓝牙链接
		onUnload() {
			console.log('关闭蓝牙连接')
			bluetooth.closeBLEConnection();
			bluetooth.closeBluetoothAdapter();
		},
		onLoad() {
            this.deviceId = uni.getStorageSync("deviceId") || "暂无信息";
			this.serviceId = uni.getStorageSync("serviceId") || "暂无信息";
			this.notifyId = uni.getStorageSync("notifyId") || "暂无信息";
			this.writeId = uni.getStorageSync("writeId") || "暂无信息";
			bluetooth.openBluetoothAdapter();
		},
		methods: {
			reconnect(){
				uni.showLoading({
					mask: true,
					title: '正在连接设备'+this.deviceId
				})
				bluetooth.reconnect();
			},
			//搜索周边设备
			startBluetoothDeviceDiscovery() {
				uni.showLoading({
					title: '蓝牙搜索中'
				})

				let self = this;
				self.devicesList = [];

				setTimeout(() => {
					uni.startBluetoothDevicesDiscovery({
						success: res => {
							uni.hideLoading();
							uni.onBluetoothDeviceFound(devices => {
								//console.log("发现设备: " + JSON.stringify(devices));
								//不重复,就添加到devicesList中,
								if (!self.devicesList.some(item => {
										return item.deviceId === devices.devices[0].deviceId
									})) {
									self.devicesList.push(devices.devices[0])
								}
							});
						},
						fail: res => {
							uni.hideLoading();
							uni.showToast({
								title:`搜索设备失败` + JSON.stringify(err),
								icon:"none"
							})
						}
					})
				}, 200)
			},

			//停止搜索蓝牙设备
			stopBluetoothDevicesDiscovery() {
				uni.hideLoading();
				bluetooth.stopBluetoothDevicesDiscovery();
			},


			//选中设备
			async select_deviceId(item) {
				this.deviceId = item.deviceId;
				bluetooth.deviceId = item.deviceId;
				uni.setStorageSync('deviceId', bluetooth.deviceId);

				this.serviceList = [];

				try {
					//1.链接设备
					await bluetooth.createBLEConnection();
					
					uni.showLoading({
						title: '正在获取蓝牙设备服务'
					})
					//2.寻找服务
					await bluetooth.getBLEDeviceServices().then(res=>{
						uni.hideLoading()
						this.serviceList = res;
					});				
				} catch (e) {
					uni.hideLoading()
					console.log("e: " + JSON.stringify(e));
				}
			},

			//选中服务
			async select_service(res) {
				let self = this;
				bluetooth.serviceId = res.uuid;
				uni.setStorageSync('serviceId', res.uuid);
				try {
					let result = await bluetooth.getBLEDeviceCharacteristics();
					setTimeout(function() {
						uni.showToast({
							title:"已连接打印机，请测试打印",
							icon:"none"
						})
					}, 500);
					
				} catch (e) {
					console.log("e: " + JSON.stringify(e));
				}
			},

			//打印一次
			pickUpOnce() {
				uni.showToast({
					title:"正在为您打印...",
					mask:true,
					icon:"none",
					duration:2000
				})
				bluetooth.notifyBLECharacteristicValue();
				let self = this;
				setTimeout(() => {
					self.writeBLECharacteristicValue();
				}, 500);
			},

			//写入控制命令
			async writeBLECharacteristicValue() {
                // 如果您遇到打印问题或者其他方面需求，可添加微信：chengjn1314(宁哥)咨询
				// 如果您遇到打印问题或者其他方面需求，可添加微信：chengjn1314(宁哥)咨询
				// 如果您遇到打印问题或者其他方面需求，可添加微信：chengjn1314(宁哥)咨询
				
				//祝你测试打印一切顺利，现在开始打印模板（模板可定制调试）
				let printerJobs = new PrinterJobs();
				printerJobs
					.setSize(1, 1)
					.print(printerUtil.fillAround('加油小票'))
					.print('')
					.setAlign('lt')
				    .print('油品名称：92#汽油')
					.print('用户卡号：00000259')
					.print('加油数量：48.07升')
					.print('油品价格：8.05元')
					.print('加油金额：387元')
					.print('结算方式：用户卡')
					.print('卡余额：413.87元')		
					.print('单位名称：供电局')
					.print('油站名称：桂通石油桥头加油站')
					.print('加油时间：2022-10-13 11：34：59')
					.print('')
					.print(printerUtil.fillAround('谢谢惠顾'))
					.println()
				;
				let buffer = printerJobs.buffer();
				this.printbuffs(buffer);
			},

			printbuffs(buffer) {
				// 1.并行调用多次会存在写失败的可能性
				// 2.建议每次写入不超过20字节
				// 分包处理，延时调用
				const maxChunk = 20;
				const delay = 20;
				for (let i = 0, j = 0, length = buffer.byteLength; i < length; i += maxChunk, j++) {
					let subPackage = buffer.slice(i, i + maxChunk <= length ? (i + maxChunk) : length);
					setTimeout(this.printbuff, j * delay, subPackage);
				}
			},

			printbuff(buffer) {
				bluetooth.writeBLECharacteristicValue(buffer);
			},

		}
	}
</script>

<style>
	.content {}

	page {
		color: #333;
	}

	button {
		margin: 10upx;
	}

	.devices_summary {
		margin-top: 5rpx;
		padding: 20rpx;
		font-size: 30rpx;
	}

	.device_list {
		margin: 5rpx 20rpx 5rpx 20rpx;
		border: 1rpx solid #ddd;
		border-radius: 10rpx;
		background-color: #FdFdFd;
		min-height: 0rpx;
		max-height: 400rpx;
		width: 700rpx;

	}

	.device_item {
		border-bottom: 1rpx solid #ddd;
		padding: 20rpx;
		color: #666;

	}

	.device_item_hover {
		background-color: rgba(0, 0, 0, .1);
	}

	.connected_info {
		position: fixed;
		bottom: 0;
		width: 100%;
		background-color: #F0F0F0;
		padding: 10px;
		padding-bottom: 20px;
		margin-bottom: env(safe-area-inset-bottom);
		font-size: 14px;
		min-height: 100px;
		box-shadow: 0px 0px 3px 0px;
	}

	.connected_info .operation {
		position: absolute;
		display: inline-block;
		right: 30px;
	}
</style>
